package com.itgaohe.controller;


import com.itgaohe.common.context.UserContext;
import com.itgaohe.dao.entity.Chat;
import com.itgaohe.dto.resp.ChatMessageResponseDTO;
import com.itgaohe.service.ChatService;
import com.itgaohe.service.WebsocketServerEndpoint;
import com.itgaohe.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chat")
@Tag(name = "聊天室", description = "用户相关操作")
public class ChatController {

    @Autowired
    private ChatService chatService ;

    @Operation(summary = "根据friendId获取好友")
    @GetMapping("/{friendId}")
    public Result getChatHistory(@PathVariable("friendId") Long friendId) {
        // 假设当前用户ID为1（实际应从认证信息获取）
        Long currentUserId = UserContext.getUser().getId() ;

        List<Chat> messages = chatService.getChatHistory(currentUserId, friendId);
        ChatMessageResponseDTO chatMessageResponseDTO = new ChatMessageResponseDTO();
        chatMessageResponseDTO.setId(currentUserId);
        chatMessageResponseDTO.setData(messages);
        return Result.ok(chatMessageResponseDTO);
    }

    /**
     * 用户消息发送
     */
    @Operation(summary = "发送消息")
    @PostMapping("/send")
    public Result sendMessage(@RequestBody Chat chat){

        try {
            WebsocketServerEndpoint endpoint = new WebsocketServerEndpoint();
            endpoint.sendTo(chat);
            return Result.ok() ;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("发送失败");
        }
    }
}
